package cn.jinjimi.app.main.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import bolts.Continuation;
import bolts.Task;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.Constants;
import cn.jinjimi.app.controller.PageController;
import cn.jinjimi.app.entity.LinkBean;
import cn.jinjimi.app.main.adapter.FragmentPageAdapter;
import cn.jinjimi.app.main.extend.BaseFragment;
import cn.jinjimi.app.main.widget.PagerSlidingTabStrip;
import cn.jinjimi.domain.data.dto.ConfigDTO;
import cn.jinjimi.framework.router.Router;


public class HomeFragment extends BaseFragment implements ViewPager.OnPageChangeListener {

    private ViewPager mViewPager;
    private PagerSlidingTabStrip indicator;
    private List<Fragment> fragments;
    private int position;
    private ImageView mBtnShop;

    @Override
    protected int getLayoutResourceId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initial() {
        initView();
        initData();
    }

    private void initView() {
        mViewPager = (ViewPager) findView().findViewById(R.id.vp_fragments);

        indicator = (PagerSlidingTabStrip) findView().findViewById(R.id.indicator_tabs);
        indicator.setOnPageChangeListener(this);

        EditText searchInput = (EditText) findView().findViewById(R.id.et_search);
        searchInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() != 0) {

                }
            }
        });

        searchInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    doSearch(v.getText().toString());
                }
                return false;
            }
        });

        mBtnShop = findView().findViewById(R.id.btn_shop);
    }

    private void initData() {
        loadConfig();
    }

    private void loadConfig() {

        PageController
                .requestPageConfig()
                .onSuccess(new Continuation<ConfigDTO, Void>() {
                    @Override
                    public Void then(Task<ConfigDTO> task) throws Exception {
                        if (task.isCancelled() || task.isFaulted()) {
                            return null;
                        }
                        ConfigDTO dto = task.getResult();
                        if (dto != null) {
                            showTabs(dto.getHome_cates());
                            setShop(dto.getShopLink());
                        }
                        return null;
                    }
                }, Task.UI_THREAD_EXECUTOR);
    }

    private void doSearch(String keyword) {
        if (!TextUtils.isEmpty(keyword)) {
            Router.create(getContext(), Constants.Route.PRODUCT_SEARCH_URL)
                    .addParam(Constants.BundleKey.Q, keyword)
                    .open();
        }
    }

    private void showTabs(List<LinkBean> cates) {
        LinkBean hot = new LinkBean();
        hot.label = "热门推荐 ";
        cates.add(0, hot);
        initFragment(cates);

    }

    public void initFragment(List<LinkBean> links) {
        fragments = new ArrayList<>();
        List<String> titles = new ArrayList<>();
        for (LinkBean link : links) {
            if (TextUtils.isEmpty(link.link)) {
                fragments.add(new FirstTabFragment());
            }else {
                MainWebViewFragment fragment = new MainWebViewFragment();
                Bundle bundle = new Bundle();
                bundle.putString(Constants.BundleKey.URL, link.link);
                fragment.setArguments(bundle);
                fragments.add(fragment);
            }
            titles.add(link.label);
        }
        FragmentPageAdapter adapter = new FragmentPageAdapter(getChildFragmentManager(), fragments, titles);
        mViewPager.setAdapter(adapter);
        indicator.setViewPager(mViewPager);
        setCurrentItem(position);
    }

    public void setCurrentItem(int position) {
        this.position = position;
        if (mViewPager != null && mViewPager.getAdapter() != null
                && position >= 0 && position < mViewPager.getAdapter().getCount()) {
            mViewPager.setCurrentItem(position);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onDestroyView() {
        if (fragments != null) {
            fragments.clear();
            fragments = null;
        }
        if (mViewPager.getAdapter() != null) {
            for (int i = 0; i < mViewPager.getAdapter().getCount(); i++) {
                ((FragmentPageAdapter) mViewPager.getAdapter()).getItem(i).onDestroy();
            }
        }
        super.onDestroyView();
    }

    public void setShop(final LinkBean shop) {
        if (mBtnShop != null) {
            mBtnShop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Router.create(getContext(), shop.link).open();
                }
            });
        }
    }
}
